export function buildQuery(query = {}) {
  let esc = encodeURIComponent;
  return Object.keys(query).map( (key) => {
    return esc(key) + '=' + esc(query[key])
  }).join('&');
}

export function parseQuery(qstr) {
  if (qstr.trim().length <= 0) {
    return {};
  }
  var query = {};
  var a = (qstr[0] === '?' ? qstr.substr(1) : qstr).split('&');
  for (var i = 0; i < a.length; i++) {
      var b = a[i].split('=');
      let v = b[1] || '';
      try {
        v = decodeURIComponent(b[1] || '');
      } catch (e) {
        // TODO::
      }

      query[decodeURIComponent(b[0])] = v;
  }
  return query;
}

let baseOptions = {
  credentials: 'same-origin'
};

export const get =  (url, query = {}, options = {}) => {

  let queryUrl = url;
  if (buildQuery(query) != '') {
    queryUrl += '?' + buildQuery(query);
  }

  return fetch(queryUrl, Object.assign({}, baseOptions, options))
}

export const post =  (url, form = {}, options = {}, query = {}) => {
  let formbody = Object.keys(form).map( key =>  encodeURIComponent(key)+'='+encodeURIComponent(form[key]) ).join('&');
  let _baseOptions = Object.assign({}, baseOptions, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'      
    },
    body: formbody
  });

  let queryUrl = url;
  if (buildQuery(query) != '') {
    queryUrl += '?' + buildQuery(query);
  }
  return fetch(queryUrl, Object.assign({}, _baseOptions, options)).then(res => {
    let json = res.json();
    json.then(data => {
      if (typeof data.datas == 'undefined') {
        data.datas = {};
      }
      data.from = queryUrl;
      return data;
    })
    res.json = () => {
      return json;
    };
    json.then((data) => {
      let url = res.url;
      if (data.errorCode == '000007' || data.errorCode == '000005') {
        post(userLogoutAPI())
        .then(res => res.json())
        .then(data => {
          window._userName = '';
          console.log('自动登出'); 
          console.log(window.location.href);
          if ( ( window.location.href.indexOf('login') != -1 ) 
            || ( window.location.href.indexOf('hgsport') != -1 ) ) {
            console.log('不需要跳转');
          } else {
            console.log('要跳转');
            window.location.href = '/';
          }
        });
      }
    });

    return res;
  });
}

// export const post =  (url, form = {}, options = {}, query = {}) => {
//   let formbody = Object.keys(form).map( key =>  encodeURIComponent(key)+'='+encodeURIComponent(form[key]) ).join('&');
//   let _baseOptions = Object.assign({}, baseOptions, {
//     method: 'POST',
//     headers: {
//       'Content-Type': 'application/x-www-form-urlencoded',
//       "web_flag":"e0",
//       "device_type":"wap",
//       "platform_type":"wap",
//       'device_id':'C01F45E97463E053222ABB584FE13859',
//       'web_domain':'168ylc_domian',
//       'client_ip':'199.22.431.14',
//       'user_name':'user_name',
//       "access_token":"25ef028428f6b3b1f6cae31b37dd3c06e78dd6ad81893962b500f407e66a445d7433ee88ce834ef284c6b557c7976c58a8f0caf6d223b819f40b118cb65a926bf51f4910c10be008"      
//     },
//     body: formbody
//   });

//   let queryUrl = url;
//   if (buildQuery(query) != '') {
//     queryUrl += '?' + buildQuery(query);
//   }
//   return fetch(queryUrl, Object.assign({}, _baseOptions, options)).then(res => {

//     let json = res.json();
      
//     json.then(data => {
//       if (typeof data.datas == 'undefined') {
//         data.datas = {};
//       }
//       data.from = queryUrl;

//       return data;
//     })

//     res.json = () => {
//       return json;
//     };

//     json.then((data) => {
//       let url = res.url;
//       if (data.errorCode == '000007' || data.errorCode == '000005') {
//         post(userLogoutAPI())
//         .then(res => res.json())
//         .then(data => {
//           window._userName = '';
//           console.log('自动登出'); 
//           console.log(window.location.href);
//           if ( ( window.location.href.indexOf('login') != -1 ) 
//             || ( window.location.href.indexOf('hgsport') != -1 ) ) {
//             console.log('不需要跳转');
//           } else {
//             console.log('要跳转');
//             window.location.href = '/';
//           }
//         });
//       }
//     });

//     return res;
//   });
// }


export const put =(url, form, options, query ={}) => {
  let formbody = Object.keys(form).map( key =>  encodeURIComponent(key)+'='+encodeURIComponent(form[key]) ).join('&');
  let _baseOptions = Object.assign({}, baseOptions, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: formbody
  });3

  let queryUrl = url;
  if (buildQuery(query) != '') {
    queryUrl += '?' + buildQuery(query);
  }

  return fetch(queryUrl, Object.assign({}, _baseOptions, options));
};


export const registerAPI = () => {
  return `/user/register`;
};

export const codeUrl = ()=>{
  return "resources-code.jpg"
  // return "http://192.168.5.126:8080/resources-code.jpg"
}

export const loginAPI = ()=>{
  return "/user/login"
}

export const logoutAPI =()=>{
  return `/user/logout`
}
//用户信息
export const userInfoAPI = () => {
  return `/member/user/info`;
}
export const changeUserInfoAPI = () => {
  return `/member/user/modify`;
}
//用户消息
export const userMessageAPI = () => {
  return `/member/message/list`;
}

export function changePwdAPI() {
  return `/member/password/login`;
}

export function changeWithdrawPwdAPI() {
  return `/member/password/withdraw`;
}
// 充值记录
export const chargeRecordHistoryAPI = () => {
  return `/member/record/deposit`;
}

export const chargeWithdrawHistoryAPI = () => {
  return `/member/record/withdraw`;
}


// 投注记录
export function OrderlistAPI(params) {
  return "/cp/order/list"
}

export function  bindBankAPI(params) {
  return "/member/bank/bind"
}
// 获取银行列表
export function banklistAPI() {
  return `/member/bank/list`;
}
// 获取用户银行列表
export function userbanklistAPI() {
  return `/member/bank/user`;
}

export function BankTransferType(params) {
  return "/member/selectBankTransferType"
}

//充值
export function fastPayList(params) {
  return "/member/selectIncFastPayList"
}

export function bankPayList(params) {
  return "/member/selectIncBankPayList"
}

export function saveIncBankPayAPI(params) {
  return "/member/user/saveIncBankPay"
}

export function allPayList(params) {
  return "/member/selectPayList"
}

export function payTraditionBankAPI(params) {
  return "/member/pay/tradition/bank"
}

export function payOnlineQuickAPI(params) {
  return "/member/user/pay/online/scan"
}
// http://mgm488.cc/member/pay/online/saoma/list
// http://mgm488.cc/member/pay/chuantong/bank/list
// http://mgm488.cc/member/pay/all/list
export function chargeAlllistAPI() {
  return `/member/pay/all/list`;
}
// 提现
export function userWithdrawAPI() {
  return `/member/withdraw/save`;
}

//今日盈亏
export function getRecordsInfoAPI() {
  return `/member/records/info`;
}


//获取在线客服 帮助中心等模板
export function getTemplateAPI() {
  return '/main/template/list'
}
